/**
 * ajax 模块，可以将 axios 替换成 $.ajax 等
 */
import axios from 'axios';
import globalConfig from '../config'
import { Notification, Loading } from 'element-ui'

const GET_I18N = 'static/i18n/'
// 设置全局loading
let loadingInstance = {}
// 发送条数
let ajaxNum = 0
let overNum = 0

const init = function () {
  axios.interceptors.request.use(function (config) {
    // 打开loading
    loadingInstance = Loading.service({
      lock: true,
      text: '加载中...',
      spinner: 'el-icon-loading',
      background: 'rgba(0, 0, 0, 0)'
    })
    // 需要加载loading的接口才计算
    !config.noLoading && ajaxNum++
    // 拦截request请求，带上加载中样式, 默认白色背景
    loadingInstance = Loading.service()
    if (config.url.indexOf(GET_I18N) < 0) {
      config.url = window.host.gatewayDomain + config.url
    }
    var cookies = globalConfig.getCookies()
    config.url += 'access_token=' + (cookies['access_token'] || 'b03f1428-6d12-4283-b680-39f1fb88afd4')
    if (!config.data) config.data = {}
    return config;
  }, function (err) {
    over(err)
    return Promise.reject(err)
    // return (err)
  })

  // Add a response interceptor
  axios.interceptors.response.use(function (response) {
    over(response)
    const {status, data} = response;

    if (status === 200) {
      // 如果不出现错误，直接向回调函数内输出 data
      if (data.error === 'SUCCESS') {
        return data
      } else {
        if (data.message) {
          Notification({
            title: '错误',
            message: data.message,
            type: 'error',
            customClass: 'el-error-msg',
            duration: 2000
          })
        }
        return data
      }
    } else {
      return response;
    }
  }, function (error) {
    over(error)
    const {response} = error;

    // 这里处理错误的 http code
    if (!response || response.status === 404) {
      if (!response) {
        Notification({
          title: '错误',
          message: 'access_token已失效请重新登录',
          type: 'error',
          customClass: 'el-error-msg',
          duration: 1500,
          onClose() {
            process.env.NODE_ENV !== 'development' && (window.location.href = window.host.loginUrl)
          }
        })
      } else {
        console.log('404 error %o' + error);
      }
    }
    // return (error)
    // Do something with response error
    return Promise.reject(error.message);
  });
};

const over = function(res) {
  // 需要加载loading的接口才计算
  !res.config.noLoading && overNum++
  if (overNum === ajaxNum) {
    loadingInstance.close()
  }
}

export default {
  init
}
